package com.system.service.photo.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.constant.AliyunConstants;
import com.system.constant.HTTPStatus;
import com.system.constant.QiniuyunConstants;
import com.system.entity.Teacher;
import com.system.entity.photo.Photo;
import com.system.mapper.photo.PhotoMapper;
import com.system.response.Result;
import com.system.response.photo.PhotoDtoResponse;
import com.system.service.photo.PhotoService;
import com.system.util.AliyunUtil;
import com.system.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.system.constant.CommonConst.STATUS_SUCCESS;

/**
 * <p>
 * 照片表 服务实现类
 * </p>
 *
 * @author zfc
 * @since 2024-02-26
 */
@Slf4j
@Service
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements PhotoService {

    @Autowired
    private PhotoMapper photoMapper;


    /**
     * @param photoDtoResponse
     * @return
     */
    @Override
    public Result photoList(PhotoDtoResponse photoDtoResponse) {

        if (photoDtoResponse.getPageSize() == null || photoDtoResponse.getPageSize() < 0)
            photoDtoResponse.setPageSize(1);
        if (photoDtoResponse.getPageNum() == null || photoDtoResponse.getPageNum() < 10)
            photoDtoResponse.setPageNum(10);
        PageHelper.startPage(photoDtoResponse.getPageSize(), photoDtoResponse.getPageNum());
        List<Photo> photoList = photoMapper.selectList(
                new LambdaQueryWrapper<Photo>()
                        .eq(!StringUtils.isNull(photoDtoResponse.getDelete()), Photo::getIsDelete, 0)
                        .orderByAsc(Photo::getCreateDate)
        );

        Integer count = photoMapper.selectCount(
                new LambdaQueryWrapper<Photo>()
                        .eq(!StringUtils.isNull(photoDtoResponse.getDelete()), Photo::getIsDelete, 0)
        );

        PageInfo<Photo> info = new PageInfo<>(photoList);
        info.setSize(count);

        return new Result().setCode(HTTPStatus.SUCCESS).setData(info);
    }

    /**
     * @param photo_id
     * @param is_delete
     * @return
     */
    @Override
    public Result deletePhoto(Integer photo_id, Integer is_delete) {
        if (is_delete == STATUS_SUCCESS) {
            //将图片改为删除逻辑
            Photo photo = new Photo();
            photo.setIsDelete(is_delete);
            photoMapper.update(photo,
                    new LambdaQueryWrapper<Photo>()
                            .eq(Photo::getId, photo_id)
            );
        } else {
            //将图片彻底删除
            photoMapper.delete(
                    new LambdaQueryWrapper<Photo>()
                            .eq(Photo::getId, photo_id)
            );
        }

        return new Result().setCode(HTTPStatus.SUCCESS).setMessage("操作成功！");
    }

    /**
     * @param photo
     * @return
     */
    @Override
    public Result frontendAddPhoto(Photo photo) {
        String photoName;
        switch (photo.getType()) {
            case 0:
                //前端七牛云上传
                photoName = frontendUploadImageAddressGetPhotoName(photo.getUrl(), QiniuyunConstants.qiniuImageDomain);
                log.info("匹配成功 photoName : ",photoName);
                photo.setPhotoName(photoName);
                break;
            case 1:
                //前端阿里云上传
                photoName = frontendUploadImageAddressGetPhotoName(photo.getUrl(), "https://" + AliyunConstants.bucketName + "." + AliyunConstants.endpoint);
                log.info("匹配成功 photoName : ",photoName);
                photo.setPhotoName(photoName);
                break;
            default:
                return new Result().setCode(HTTPStatus.ERROR).setMessage("上传类型选择错误！");
        }
        photoMapper.insert(photo);
        return new Result().setCode(HTTPStatus.SUCCESS).setMessage("操作成功！");
    }

    /**
     * 通过前端上传的图片地址,获取图片名称
     * @param image_url :https://qiniuyun.zfc.life/sm-frontend/2024/3/20471073.jpg
     * @param domain :https://qiniuyun.zfc.life/
     * @return
     */
    public static String frontendUploadImageAddressGetPhotoName(String image_url,String domain){
        // 定义正则表达式 表示以字符串 QiniuyunConstants.qiniuImageDomain 开头，后面跟着任意字符的零个或多个
            String regex = Pattern.quote(domain) + "(.*)";
        //创建Pattern对象
        Pattern pattern = Pattern.compile(regex);

        //创建Matcher对象，在文本中查找匹配的内容
        Matcher matcher = pattern.matcher(image_url);

        if (matcher.find()){
            // 获取后面的内容
            String content = matcher.group(1);
            return content;
        }

        return "mapping error";
    }

    public static void main(String[] args) {
        //测试正则零零零零
        String image_url = "https://qiniuyun.zfc.life/sm-frontend/2024/3/20471073.jpg";
        String domain = "https://qiniuyun.zfc.life/";
        String s = frontendUploadImageAddressGetPhotoName(image_url, domain);
        System.out.println("s = " + s);
    }
    /**
     * @param photo
     * @return
     */
    @Override
    public Result backendAddPhoto(Photo photo) {

        String photo_url;

        switch (photo.getType()) {
            case 0:
                //七牛云上传
                //因为前端上传的时候是先将图片上传成功后，返回的照片名称。将照片名称存起来。
                photo.setPhotoName(photo.getUrl());

                photo_url = QiniuyunConstants.qiniuImageDomain + photo.getUrl();
                log.info("七牛云图片访问地址：", photo_url);

                photo.setUrl(photo_url);
                break;
            case 1:
                //阿里云上传

                //因为前端上传的时候是先将图片上传成功后，返回的照片名称。将照片名称存起来。
                photo.setPhotoName(photo.getUrl());

                //根据阿里访问照片的原则；拼接图片地址 al-sm.https://oss-cn-shanghai.aliyuncs.com/sm-frontend/098b1c01-dc09-49a0-a2a1-18ad792b026d.jpg
                photo_url = "https://" + AliyunConstants.bucketName + "." + AliyunConstants.endpoint + "/" + photo.getUrl();

                log.info("阿里云图片访问地址：", photo_url);

                photo.setUrl(photo_url);
                break;
            case 2:
                //本地上传
                break;
            default:
                return new Result().setCode(HTTPStatus.ERROR).setMessage("上传类型选择错误！");
        }
        photoMapper.insert(photo);
        return new Result().setCode(HTTPStatus.SUCCESS).setMessage("资源上传成功！");
    }

}
